<?php

namespace wechat;

use app\common\controller\Service;
use app\common\library\job\MysqlJob;
use EasyWeChat\Factory;
use EasyWeChat\Kernel\Exceptions\InvalidArgumentException;
use EasyWeChat\Kernel\Exceptions\InvalidConfigException;
use EasyWeChat\Kernel\Exceptions\RuntimeException;
use EasyWeChat\Kernel\Http\StreamResponse;
use EasyWeChat\MiniProgram\Application;
use fast\Http;
use think\Queue;

class MiniProgramService extends Service
{
    private Application $app;

    public function __construct($secret)
    {
        $this->appid = $secret->appid;
        $this->secret = $secret->app_secret;

        $config = [
            'app_id' => $this->appid,
            'secret' => $this->secret,
            // 下面为可选项
            // 指定 API 调用返回结果的类型：array(default)/collection/object/raw/自定义类名
            'log' => [
                'level' => 'debug',
                'file' => __DIR__ . '/wechat.log',
            ],
        ];
        $this->app = Factory::miniProgram($config);
    }

    // 获取用户信息
    public function get_openid($code)
    {
        try {
            return $this->app->auth->session($code);
        } catch (InvalidConfigException $e) {
            return $e->getMessage();
        }
    }

    // 获取用户access_toeken
    public function access_token($data)
    {
        $tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=
        {$this->appid}&secret={$this->secret}";
        $res = Http::get($tokenUrl);
        $arr = json_decode($res, true);
        $url = 'https://api.weixin.qq.com/wxa/getwxacode?access_token=' . $arr['access_token'];
        $param['path'] = $data['path'] . '?sub_mch_id=1708486617';
        $param['scene'] = 'type=qrcode';//(string类型,必须是数字)
        $param['width'] = 430;
        $result = Http::post($url, $param);
        $ret = file_put_contents("./{$data['directory']}{$data['sub_mch_id']}.png", $result, true);
        return $this->_jsondate("SUCCESS", $res);
    }

    // 生成小程序二维码
    public function app_code($data)
    {
        $response = $this->app->app_code->getQrCode($data['path'] . '?sub_mch_id=' . $data['sub_mch_id']);
        if ($response instanceof StreamResponse) {
            $filename = $response->saveAs(ROOT_PATH . "public" . $data['directory'],
                $data['sub_mch_id'] . '.png');
            $url = request()->domain() . "{$data['directory']}{$data['sub_mch_id']}.png";
            Queue::push(MysqlJob::class, ['url' => $url, "unlink" => "{$data['directory']}{$data['sub_mch_id']}.png"]
                , "upload_file_unlink");
            return $this->_jsondate("SUCCESS", "{$data['directory']}{$data['sub_mch_id']}.png");
        }
        return $this->_jsondate("FAIL", "生成失败");
    }

    public function generate_code($data, $key)
    {
        $path = "{$data['path']}?$key={$data['param']}";
        $response = $this->app->app_code->getQrCode($path);
        if ($response instanceof StreamResponse) {
            try {
                $filename = $response->saveAs(ROOT_PATH . "public" . $data['directory'],
                    $data['param'] . '.png');
                $url = "https://vip.juanboss.com{$data['directory']}{$data['param']}.png";
                Queue::push(MysqlJob::class, ['url' => $url, "unlink" => "{$data['directory']}{$data['param']}.png"]
                    , "upload_file_unlink");
            } catch (InvalidArgumentException|RuntimeException $e) {
                return $this->_jsondate("FAIL", $e->getMessage());
            }
            return $this->_jsondate("SUCCESS", "{$data['directory']}{$data['param']}.png");
        }
        return $this->_jsondate("FAIL", "生成失败");
    }

}